/**
 * 点检
 * author luogan
 */
import React, { useRef, useState, forwardRef, useEffect } from 'react'
import { connect } from 'dva'
import { Button, message, Modal } from 'antd'
import HeadCount from '../HeadCount'
import PrefabricatedProject from '../PrefabricatedProject'
import CheckPreview from '../CheckPreview'
import router from 'umi/router'
import { withRouter } from 'umi'

import './index.styl'

const RefHeadCount = forwardRef((props, ref) => (
  <HeadCount {...props} cRef={ref} />
));
const RePrefabricatedProject = forwardRef((props, ref) => (
  <PrefabricatedProject {...props} cRef={ref} />
));

function Plan({ dispatch, location, query, headerTaps: { panes }, deviceCheck: { detailData } }) {
  const [cgBtn, setCbBtn] = useState(true)
  useEffect(() => {
    if (query.id !== undefined) {
      setCbBtn(false)
      dispatch({
        type: 'deviceCheck/getEditorMsg',
        payload: {
          id: query.id,
        }
      })
    }
  }, [dispatch, query.id])
  let data1 = {}
  let data2 = []
  const [viewData, setViewData] = useState({})
  // 预览弹框
  const [visible, setVisible] = useState(false)

  // 基本计划 配置点检设备 配置点检员 等信息ref
  const headCountRef = useRef()

  // 配置点检项目ref
  const projectRef = useRef()

  // 取消按钮，消除提示
  const cancelRef = useRef()

  // 删除新增配置预制项目的ID
  const deletId = (list) => {
    const arry = []
    list.map(item => {
      if (item.new) {
        delete item.new
        delete item.id
      }
      arry.push(item)
    })
    return arry
  }

  // 提交预览
  async function handleSubmitPreview(id) {
    //隐藏提示
    const nodata_error = document.querySelector('#nodata_error')
    if (nodata_error) {
      nodata_error.style.visibility = "inherit"
    }

    await headCountRef.current.handleSubmit()
    await projectRef.current.submitData()
    if (JSON.stringify(data1) === '{}' || !data2.length) {
      return
    }

    const viewData = {
      ...data1,
      status: id,
      id: detailData.id,
      checkTaskList: deletId(data2)
    }

    setViewData(viewData)
    if (id === 5) {
      // 编辑存草稿
      if (query && query.type === 'editor') {
        dispatch({
          type: 'deviceCheck/toCheckUpdate',
          payload: { ...viewData, id: detailData.id }
        }).then((res = { code: false }) => {
          if (res.code === '000000') {
            message.success(res.mesg)
            cancleClean()
            return
          }
          message.error(res.mesg)
        })
      } else {
        // 新增存草稿
        dispatch({
          type: 'deviceCheck/addCheck',
          payload: { ...viewData }
        }).then((res = { code: false }) => {
          if (res.code === '000000') {
            message.success(res.mesg)
            cancleClean()
            return
          }
          message.error(res.mesg)
        })
      }
      return
    }
    setVisible(true)
  }
  function cancleClean() {
    const { pathname } = location
    const panesList = panes.filter(pane => pane.key !== pathname);
    dispatch({
      type: 'headerTaps/updateHeaderTaps',
      payload: { panes: panesList },
    });
    const catchName = pathname.split('/').filter(item => item !== '').join("_")
    dispatch({
      type: 'commonAction/uploadCatch',
      payload: {
        catchObj: {
          [catchName]: [false, true]
        }
      }
    })
    dispatch({
      type: 'deviceCheck/updateSerachParams',
      payload: {
        serachParams: {
          current: 1
        }
      }
    })
    router.push({
      pathname: '/deviceCheck',
      params: {
        isRefresh: true
      }
    })
  }

  const getData1 = (value, id) => {
    data1 = value
  }

  const getData2 = (value, id) => {
    data2 = value
  }

  const handleCancel = () => {
    setVisible(false)
  }

  const cancelPlan = () => {
    const { pathname } = location
    const panesList = panes.filter(pane => pane.key !== pathname);
    if (panesList.length === 0) {
      return
    }
    let prevObj = {}
    panes.forEach((item, index) => {
      if (item.key === pathname) {
        if (index) {
          prevObj = panes[index - 1]
        } else {
          prevObj = panes[index + 1]
        }
      }
    })
    dispatch({
      type: 'headerTaps/updateHeaderTaps',
      payload: { panes: panesList },
    });
    dispatch({
      type: 'commonAction/uploadCatch',
      payload: {
        catchObj: {
          'deviceCheck_add': [false, true]
        }
      }
    })
    router.push({
      pathname: prevObj.path,
      query: prevObj.query
    })

    //隐藏提示
    const nodata_error = document.querySelector('#nodata_error')
    if (nodata_error) {
      nodata_error.style.visibility = "hidden"
    }
  }

  return (
    <div className="deviceCheck-plan">
      <RefHeadCount ref={headCountRef} getData={getData1} query={query} />
      <RePrefabricatedProject ref={projectRef} getData={getData2} query={query} />
      <div className="form-btn">
        <Button className="orange-button" onClick={() => handleSubmitPreview(1)} >提交预览</Button>
        {
          detailData && detailData.status === 5 || cgBtn ?
            <Button
              className="blue-button"
              htmlType="submit"
              onClick={() => handleSubmitPreview(5)}
            >存草稿</Button>
            :
            null
        }
        <Button className="white-button" onClick={cancelPlan}>取消</Button>
      </div>
      <Modal
        title="预览计划"
        width='1133px'
        visible={visible}
        bodyStyle={{ padding: 0 }}
        okBtn={handleCancel}
        onCancel={handleCancel}
        footer={null}
      >
        <CheckPreview viewData={viewData} handleCancel={handleCancel} query={query} />
      </Modal>

    </div>
  )
}

export default connect(({ deviceCheck, headerTaps, commonAction }) => ({
  deviceCheck, headerTaps, commonAction
}))(withRouter(Plan))
